package com.shoppingmall.config;

import com.shoppingmall.handler.LoginFailHandler;
import com.shoppingmall.handler.LoginSuccessHandler;
import com.shoppingmall.handler.ShoppinglogoutSuccessHander;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {
    @Autowired
    private UserDetailsService userDetailsService;
    @Bean
    @Autowired
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.
                csrf()
                        .disable()
                .cors()
                .and()
                .authorizeRequests()
                    .antMatchers("/goods/*","/register","/showOrder","/manger/mlogin","/user/*","/manger/getOrder")
                    .permitAll()
                    .anyRequest()
                    .authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                .loginPage("http://localhost:8080/#/login")
                .successHandler(new LoginSuccessHandler())//成功处理器，
                .failureHandler(new LoginFailHandler())//失败处理器
                .and()
                .logout()
                    .logoutUrl("/exit")
                    .invalidateHttpSession(true)
                    .logoutSuccessHandler(new ShoppinglogoutSuccessHander())

            ;

        return http.build();
    }


    @Autowired
    public void registerProvider(AuthenticationManagerBuilder builder) throws Exception {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());

        builder.authenticationProvider(daoAuthenticationProvider);

    }

}
